package com.jy.api.controller.admin;


import com.jy.api.dao.UserDao;
import com.jy.api.domain.SMSType;
import com.jy.api.domain.User;
import com.jy.api.service.UserService;
import com.jy.api.signUpReq.admin.UserSignUpReq;
import com.jy.api.util.Contens;
import com.jy.api.util.ParseErrors;
import com.jy.api.util.RedisSyncLocker;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

@RestController
@RequestMapping(value = "v1/admin/", produces = "application/json;charset=utf-8")
public class UserController {
    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    UserService userService;

    @Autowired
    UserDao userDao;

    @Autowired
    private RedisSyncLocker redisSyncLocker;

    /**
     * 用户注册
     *
     * @param userOrder
     * @return
     */
    @RequestMapping(value = "sign-up", method = RequestMethod.POST)
    public ResponseEntity userRegister(@RequestBody UserSignUpReq userOrder) throws Exception {
        return (ResponseEntity) redisSyncLocker.StringKeyLock(userOrder.getUsername(), o -> {
            //数据校
            try {
                //用户验证
                Set<ConstraintViolation<UserSignUpReq>> registerErrors =
                        validator.validate(userOrder);
                if (!registerErrors.isEmpty()) {
                    return new ResponseEntity(ParseErrors.getErrors(registerErrors), HttpStatus.BAD_REQUEST);
                }

                User user = userDao.findByUsername(userOrder.getUsername());
                if (user != null) {
                    return new ResponseEntity("账号已存在", HttpStatus.BAD_REQUEST);
                }
                String code = stringRedisTemplate.opsForValue()
                        .get(Contens.SMS_KEY.replace("MOBILE", userOrder.getUsername())
                                .replace("TYPE", SMSType.ACCOUNT.toString()));
                if (!StringUtils.equals(code, userOrder.getVerCode())) {
                    return new ResponseEntity("验证码错误", HttpStatus.BAD_REQUEST);
                }
                userService.addUser(userOrder);
                return new ResponseEntity(HttpStatus.OK);
            } catch (Exception ex) {
                logger.error("userRegister is error =>userOrder:{}", userOrder, ex);
                return new ResponseEntity("账号已存在", HttpStatus.INTERNAL_SERVER_ERROR);
            }
        });

    }

    public static void main(String[] args) {
        System.out.println("wer");
    }
}
